:-module(dz,[]).
:-use_module('de.pro').
:-use_module('wx.pro').
:-use_module('tg.pro').

de:dz_items([子,丑,寅,卯,辰,巳,午,未,申,酉,戌,亥]).
de:shuaiwang_items([长生,沐浴,冠带,临官,帝旺,衰,病,死,墓,绝,胎,养]).

de:_.dz_zi():= E:- dz:new(E,0).
de:_.dz_chou():= E:- dz:new(E,1).
de:_.dz_yin():= E:- dz:new(E,2).
de:_.dz_mao():= E:- dz:new(E,3).
de:_.dz_chen():= E:- dz:new(E,4).
de:_.dz_si():= E:- dz:new(E,5).
de:_.dz_wu():= E:- dz:new(E,6).
de:_.dz_wei():= E:- dz:new(E,7).
de:_.dz_shen():= E:- dz:new(E,8).
de:_.dz_you():= E:- dz:new(E,9).
de:_.dz_xu():= E:- dz:new(E,10).
de:_.dz_hai():= E:- dz:new(E,11).

new(Var,V):-
	de:new(Var,[count-12,value-V,type-dz]).

wuxing(Zhi,Wx):-
	new(Zhi,Z),
	1 is Z mod 3,
	Wx = Zhi.wx_earth.

wuxing(Zhi,Wx):-
	new(Zhi,Z),
	1 =\= Z mod 3,
	W is (Z - Zhi.dz_shen().value) mod 12 div 3,
	wx:new(Wx,W).

chong(Z1,Z2):-
	new(Z1,_),
	Z1.add(6) = Z2.

he(Z1,Z2,Wx):-
	new(Z1,A),
	V is (1 - A) mod 12,
	new(Z2,V),
	B is (abs(A - V) - 1) >> 1,
	(
	 B = 0 -> Wx = Z1.wx_earth();
	 B = 1 -> Wx = Z1.wx_water();
	 B = 2 -> Wx = Z1.wx_gold();
	 B = 3 -> Wx = Z1.wx_fire();
	 Wx = Z1.wx_wood()
	).

hai(Z1,Z2):-
	chong(Z1,Z),
	he(Z,Z2,_).

he(S):-
	huihe(S,4).
he(Z,S):-
	he(S),
	member(Z,S).
hui(S):-
	huihe(S,1).
hui(Z,S):-
	hui(S),
	member(Z,S).


huihe([A,B,C],D):-
	range(0,9,3,J),
	new(B,J),
	E is -D,
	A = B.add(E),
	C = B.add(D).	

xing(A,B):-
	he([E1,E2,E3]),
	(E2.value > 5 -> U2 = E2; U2 = E2.rsub(3)),
	hui([U1,U2,U3]),
	nth0(I,[E1,E2,E3],A),
	nth0(I,[U1,U2,U3],B).

%% 五行12宫
wx:shuaiwang(WX,DZ,SW):-
	WX = de{}.wx_earth(),
	A = de{}.wx_water(),
	wx:shuaiwang(A,DZ,SW).

wx:shuaiwang(WX,DZ,SW):-
	wx:new(WX,A), WX \= WX.wx_earth(),
	new(DZ,B),
	D is 3 * A,
	C = WX.dz_si().add(D).rsub(B).value,
	SW = WX.get_item(shuaiwang_items,C).

%% 天干12宫
tg:shuaiwang(Gan,DZ,SW):-
	(A = 4; A = 5),
	tg:new(Gan,A),
	NewGan = Gan.add(-2),
	tg:shuaiwang(NewGan,DZ,SW).

tg:shuaiwang(G,DZ,SW):-
	tg:yang(G),
	G.value \= 4,
	tg:wuxing(G,W),
	wx:shuaiwang(W,DZ,SW).

tg:shuaiwang(G,DZ,SW):-
	tg:yang(G,0),G.value \= 5,
	YG = G.add(-1),
	tg:shuaiwang(YG,SH,死), %阴生阳死
	new(DZ,A),
	incr(12,A,B,SH.value),
	SW = G.get_item(shuaiwang_items,B).

%% 地支藏干
hide(Zhi,GS):-
	new(Zhi,A),
	B is A mod 3,
	nth0(B, [sizhong,siji,simeng],Pred),
	call(Pred,Zhi,GS).

sizhong(Zhi,[H|T]):-
	tg:yang(H,0),
	wuxing(Zhi,W),
	tg:wuxing(H,W),
	(Zhi = H.dz_wu() ->  T = [H.tg_ji()]; T = []).

siji(Zhi,[Tu,Yu,Ca]):-
	A = Zhi.tg_wu(),
	B is Zhi.value /\ 1,
	Tu = A.add(B),
	C = Zhi.add(-1),
	sizhong(C,[Yu|_]),
	D = Zhi.add(-4),
	sizhong(D,[Ca|_]).

simeng(Zhi,[Be,Sh|Tu]):-
	tg:yang(Be),
	Be.value \= 4,
	tg:yang(Sh),
	Sh.value \= 4,
	tg:shuaiwang(Be,Zhi, 临官),
	tg:shuaiwang(Sh,Zhi, 长生),
	(Zhi = Zhi.dz_hai() -> Tu = []; Tu = [Zhi.tg_wu()]).